/***************************************************
> Copyright (C) 2024 ==QWZL== All rights reserved.
> File Name: threadPool.c
> Author:nxq
> Mail:nxq949698473@163.com 
> Created Time: 2024年07月14日 星期日 15时17分19秒
***************************************************/

#include "threadPool.h"

//创造线程池，线程数量，线程长度
struct threadPool * create_threadPool(int threads,int queue_length)
{

    threadPool *pool = NULL;//线程池结构体
    pool =(threadPool*) malloc(sizeof(threadPool));
    memset(pool,0,sizeof(threadPool));

    pool->tids = (pthread_t *)malloc(sizeof(pthread_t) * threads);//线程ID
    memset(pool->tids,0,sizeof(pthread_t) * threads);

    pool->queue_max_length = queue_length;//初始化线程最大长度

    sem_init(&pool->semw,0,queue_length);//初始化写信号量
    sem_init(&pool->semr,0,0); //初始化读信号量

    pthread_mutex_init(&pool->mutex,NULL);//初始化互斥锁

    pool->threads = threads;//初始化线程数量

    pool->queue = create_queue();//创造队列

    //创建n个消费线程
    int ret = 0; 
    int i = 0;          
    for(i = 0;i < threads;i++)
    {
        ret = pthread_create(&pool->tids[i],NULL,consumer,pool);
        if(ret != 0)
        {
		    perror("pthread_create");
		    exit(-1);
	    }
    }
    return pool;
}

void  destroy_threadPool(struct threadPool  *pool)
{
    int i = 0;

    //释放信号量
    sem_destroy(&pool->semr);
    sem_destroy(&pool->semw);
    //释放锁
    pthread_mutex_destroy(&pool->mutex);
    //
    for(int i = 0; i < pool->threads; i++)
	{
		sem_post(&pool->semr);
	}
    //回收线程资源
    printf("threads:%d\n",pool->threads);
    for(i = 0; i < pool->threads; i++)
    {
        pthread_join(pool->tids[i],NULL);//等待所有线程执行结束
    }
    //释放pool->tids
    free(pool->tids);
    //释放pool
    free(pool);
    pool = NULL;
}
